NULL/*
 * File:   main.cpp
 * Author: ScaV
 *
 * Created on October 18, 2011, 5:13 PM
 */

#include "scanner.h"
#include "parser.h"
#include "tables.h"
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <windows.h>

using namespace std;
/*
 *
 */
int main(int argc, char** argv) {
try {
	char *infile, *outfile;
	if (argc < 2)
		throw "1 or 2 parameters required INPUT [OUTPUT]";
	if (argc == 2) {
		infile = new char[strlen(argv[1])];
		strcpy(infile, argv[1]);
		outfile = new char[4];
		strcpy(outfile, "CON");
	} else {
		infile = new char[strlen(argv[1])];
		strcpy(infile, argv[1]);
		outfile = new char[strlen(argv[2])];
		strcpy(outfile, argv[2]);
	}

	lexeme *lx;
	vector<lexeme*> result;
	vector<lexeme*>::iterator iter;
	scanner a(infile);
	tables table(2, 2, 2, 2, 2);
	char *name, *type;
	ofstream maintable;

//Build tables
	for (int i = 0; !a.eof() ; ++i) {
		lx = a.getNextLex();
		result.push_back(lx);
		if (lx->type == LEX_END)
			break;
		table.add(lx);
	}
//Parsing
	parser ll1(&result);
	ll1();
//Output to files
	maintable.open(outfile, ios::out);
	if (!maintable.is_open())
		throw "Can't open main output file!";
	for (iter = result.begin(); iter != result.end(); ++iter) {
		lx = *iter;
		name = lx->getName();
		type = lx->getType();
		maintable << lx->line
				<< "\t" << type
				<< "\t" << *lx->index
				<< "\t\t\t<" << name
				<< ">" << endl;
		delete[] name;
		delete[] type;
	}
	maintable.close();
	CreateDirectoryA("hashtable", NULL);
	table.unknown->print("hashtable/unknown.txt");
	table.keyword->print("hashtable/keyword.txt");
	table.constant->print("hashtable/constant.txt");
	table.identificator->print("hashtable/identificator.txt");
	table.separator->print("hashtable/separator.txt");
} catch (const char *str) {
	cout << "[FATAL ERROR] " << str << endl;
	return 1;
}
	return 0;
}

